﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;

namespace LDM.Framework.MemoryCache
{
    public class MicrosoftMemoryCache : Caches.IMemoryCache
    {
        IMemoryCache _memoryCache;

        public MicrosoftMemoryCache()
        {
            _memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(Options.Create(new MemoryCacheOptions()));
        }

        public T Get<T>(string key) where T : class
        {
            T value;
            _memoryCache.TryGetValue<T>(key, out value);
            return value;
        }

        public T GetFromCacheFirst<T>(string key, Func<T> factory, double? durationMinute = null) where T : class
        {
            T value;
            if (!_memoryCache.TryGetValue<T>(key, out value) || value == null)
            {
                value = factory();
                Set(key, value, durationMinute);
            }
            return value;
        }

        public void RemoveCache(string key)
        {
            _memoryCache.Remove(key);
        }

        public void Set<T>(string key, T obj, double? durationMinute = null) where T : class
        {
            if (durationMinute.HasValue)
                _memoryCache.Set(key, obj, TimeSpan.FromMinutes(durationMinute.Value));
            else
                _memoryCache.Set(key, obj);
        }
    }
}
